package com.handa.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.handa.common.entity.LoginUser;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    private final String secret = "zhangqiao";

    private final Long expiration = 36000000L;

    public String generateToken(LoginUser loginUser) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim("User.name", loginUser.getUsername())
                .withClaim("User.nickname", loginUser.getNickname())
                .withClaim("User.id", loginUser.getUserId())
                .withClaim("Token.id", loginUser.getTokenId())
                .withClaim("Role.id", loginUser.getRoleId())
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(algorithm);
    }

    public LoginUser parseToken(String token) {
        LoginUser loginUser = new LoginUser();
        try {
            DecodedJWT jwt = JWT.decode(token);
            loginUser.setJwt(token);
            loginUser.setUsername(jwt.getClaim("User.name").asString());
            loginUser.setTokenId(jwt.getClaim("Token.id").asString());
            loginUser.setRoleId(jwt.getClaim("Role.id").asInt());
            loginUser.setUserId(jwt.getClaim("User.id").asLong());
            loginUser.setNickname(jwt.getClaim("User.nickname").asString());
            return loginUser;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /*
     * 判断token是否过期
     * */
    public boolean isTokenValid(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWT.require(algorithm).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * 刷新token
     * */

    public String refreshToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            String username = jwt.getSubject();
            Algorithm algorithm = Algorithm.HMAC256(secret);

            Date now = new Date();
            Date expiryDate = new Date(now.getTime() + expiration);

            return JWT.create()
                    .withSubject(username)
                    .withIssuedAt(now)
                    .withExpiresAt(expiryDate)
                    .sign(algorithm);
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}